//import 'mqtt/message.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

class Mqtt {
  final String Serve;
  final int port;
  final String clientIdentififier;
  final String username;
  final String password;
  MqttClient mqttclient;
  MqttQos qos;

  Mqtt(this.Serve, this.port, this.clientIdentififier, this.username,
      this.password) {
//TODO
    this.mqttclient = MqttServerClient.withPort(
        this.Serve, this.clientIdentififier, this.port);
    this.qos = MqttQos.atLeastOnce;
    this.mqttclient.logging(on: false);
    this.mqttclient.keepAlivePeriod = 30;
    this.mqttclient.onConnected = _onConnected;
    this.mqttclient.onDisconnected = _onDisconnected;
    this.mqttclient.onSubscribed = _onSubscribed;
    this.mqttclient.onSubscribeFail = _onSubscribeFail;
    this.mqttclient.pongCallback = pong;
  }

  void _onConnected() {
    print('onConnected');
  }

  void _onDisconnected() {
    print('_onDisconnected');
  }

  void _onSubscribed(String topic) {
    print('_onSubscribed');
  }

  void _onSubscribeFail(String topic) {
    print('_onSubscribeFail');
  }

  void pong() {
    print('pong');
  }

//TODO
  void connect() {
    this.mqttclient.connect(this.username, this.password);
  }

  void disconnect() {
    this.mqttclient.disconnect();
  }

  void subscribe(String subtopic) {
    this.mqttclient.subscribe(subtopic, this.qos);
  }

  void pubscribe(String pubtopic, String msg) {
    MqttClientPayloadBuilder builde = new MqttClientPayloadBuilder();
    builde.addString(msg);
    this.mqttclient.publishMessage(pubtopic, this.qos, builde.payload);
  }
}
